package com.xml.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.xml.domain.Book;
import com.xml.domain.Borrow;
import com.xml.domain.Reader;
import com.xml.utils.HibernateUtils;


public class BorrowDaoImpl implements BorrowDao {

	@Override
	public boolean borrowBook(String readerId, String isbn) {
		Session session = HibernateUtils.getSession();
		Transaction transaction = null;
		try{
			transaction = session.beginTransaction();
			Query query1 = session.createQuery("from Reader where readerId = ?");
			query1.setParameter(0,readerId);
			Reader reader = (Reader) query1.list().get(0);
			
			Query query2 = session.createQuery("from Book where isbn = ?");
			query2.setParameter(0,isbn);
			Book book = (Book) query2.list().get(0);
			Borrow borrow = new Borrow();
			borrow.setBook(book);
			borrow.setReader(reader);
			session.save(borrow);
			
			reader.setNumOfBorrow(reader.getNumOfBorrow()+1);
			session.update(reader);
			
			book.setState(1);
			session.update(book);
			transaction.commit();
		}catch (Exception e) {
			if(transaction!=null){
				transaction.rollback();
				return false;}
		}finally{
			session.close();
		}
		return true;
	}

	@Override
	public boolean returnBook(String readerId, String isbn) {
		Session session = HibernateUtils.getSession();
		Transaction transaction = null;
		try{
			transaction = session.beginTransaction();
			Query query1 = session.createQuery("from Reader where readerId = ?");
			query1.setParameter(0,readerId);
			Reader reader = (Reader) query1.list().get(0);
			
			Query query2 = session.createQuery("from Book where isbn = ?");
			query2.setParameter(0,isbn);
			Book book = (Book) query2.list().get(0);
			
			String hql = "from Borrow b inner join fetch b.reader inner join fetch b.book where b.reader.readerId = ? and b.book.isbn = ?";
			Query query= session.createQuery(hql);
			query.setParameter(0, readerId);
			query.setParameter(1, isbn);
			Borrow borrow = (Borrow) query.list().get(0);
			session.delete(borrow);
			reader.setNumOfBorrow(reader.getNumOfBorrow()-1);
			session.update(reader);
			
			book.setState(0);
			session.update(book);
			transaction.commit();
		}catch (Exception e) {
			if(transaction!=null){
				transaction.rollback();
				return false;}
		}finally{
			session.close();
		}
		return true;
	}

	@Override
	public List<Borrow> searchBorrowInfo(String readerId) {
		Session session = HibernateUtils.getSession();
		Transaction transaction = session.beginTransaction();
		String hql = "from Borrow b inner join fetch b.reader inner join fetch b.book where b.reader.readerId = ?";
		Query query= session.createQuery(hql);
		query.setParameter(0, readerId);
		List<Borrow> list = query.list();
		transaction.commit();
		session.close();
		return list;
	}

}
